package tree;

public class InsertIntoBinarySearchTree701 {
    public TreeNode insertIntoBST(TreeNode root, int val) {
        if (root == null) {
            // 创建节点, 可能被作为上级的子节点
            return new TreeNode(val);
        }
        if (root.val == val) {
            return root;
        }
        // 更新root节点的孩子, 有可能变了, 有可能没变
        if (val < root.val) {
            root.left = insertIntoBST(root.left, val);
        } else {
            root.right = insertIntoBST(root.right, val);
        }
        return root;
    }

    public TreeNode insertIntoBSTLooply(TreeNode root, int val) {
        if (root == null) {
            return new TreeNode(val);
        }
        TreeNode parent = null;
        TreeNode n = root;
        while (n != null) {
            if (val == n.val) {
                return n;
            } else if (val < n.val) {
                parent = n;
                n = n.left;
            } else {
                parent = n;
                n = n.right;
            }
        }
        n = new TreeNode(val);
        if (val < parent.val) {
            parent.left = n;
        } else {
            parent.right = n;
        }
        return root;
    }
}
